#include "loadprogramwnd.h"
#include <QtGui>
#include "wndmanager.h"
#include "syscontroller.h"

//------------------------------------------------------------------------------
// PUBLIC INTERFACES
//------------------------------------------------------------------------------

LoadProgramWnd::LoadProgramWnd(QWidget *parent)
	: QWidget(parent),
	  sys_(SysController::instance())
{
	ui.setupUi(this);

	// setup files viewer
	
	fsModel = new QFileSystemModel;
	fsModel->setRootPath(QDir::currentPath());
	fsModel->setFilter(QDir::Files);

	ui.filesView->setModel(fsModel);
	ui.filesView->setRootIndex(fsModel->index(QDir::currentPath()));
    ui.filesView->verticalHeader()->setHidden(true);
    ui.filesView->horizontalHeader()->setHidden(true);
    ui.filesView->setColumnHidden(1, true);
    ui.filesView->setColumnHidden(2, true);
    ui.filesView->setColumnHidden(3, true);
    ui.filesView->setShowGrid(false);
	ui.filesView->setColumnWidth(0, ui.filesView->width() - WndManager::kEdgePadding);
//	int rowHeight = ui.filesView->height() / kTableRows;
//	for(int row = 0; row < fsModel->rowCount(); ++row){
//		ui.filesView->setRowHeight(row, rowHeight);
//	}
//	ui.filesView->
//	TODO: Control columns' height

    ui.filesView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui.filesView->setSelectionMode(QAbstractItemView::SingleSelection);

	connect(ui.okButton, SIGNAL(clicked()), this, SLOT(wndShouldReturn()));
	connect(ui.cancelButton, SIGNAL(clicked()), this, SLOT(wndShouldReturn()));
	connect(ui.filesView, SIGNAL(pressed(const QModelIndex&)), 
						  this, SLOT(fileSelected(const QModelIndex&)));
}

LoadProgramWnd::~LoadProgramWnd()
{
	delete ui.okButton;
	delete ui.cancelButton;
	delete ui.upButton;
	delete ui.downButton;
	delete ui.fileLabel;
	delete ui.filesView;
	delete fsModel;
}

//------------------------------------------------------------------------------
// SLOTS
//------------------------------------------------------------------------------

void LoadProgramWnd::pageScrolled()
{
}

void LoadProgramWnd::fileSelected(const QModelIndex& index)
{
	if(index.isValid()){
		QModelIndex fileNameIndex = index.sibling(index.row(), 0);
		ui.fileLabel->setText(fsModel->fileName(fileNameIndex));
	}
}

void LoadProgramWnd::wndShouldReturn()
{
	QPushButton *button = qobject_cast<QPushButton *>(sender());
	if(button == ui.okButton){
		if(getSelectedFileName().isEmpty()){
			qDebug() << "NO VALID FILE NAME, CANNOT LOAD!";
			return;
		}else{
			sys_->LoadProgram(getSelectedFileName());
		}	
	}
	WndManager::gotoWnd(WndManager::kWndMainMenu);
}

//------------------------------------------------------------------------------
// PRIVATE FUNCTIONS
//------------------------------------------------------------------------------

QString LoadProgramWnd::getSelectedFileName()
{
	QString path = ui.fileLabel->text();
	path = path.left(path.indexOf("."));
	return path;
}
